layui.use(['form', 'table', 'upload', 'laydate'], function () {
  var form = layui.form,
    table = layui.table,
    upload = layui.upload,
    laydate = layui.laydate;

  form.render();

  let editConfirmTemplateId = ""; //模板确认更新时，需要传递的id


  //列表的表格

  let tableIns = table.render({
    elem: '#dataTable',
    height: 500,
    url: containercode_url + "/enterprise/list",
    parseData: function (res) { //res 即为原始返回的数据
      return {
        "code": res.errorCode, //解析接口状态
        "msg": res.message, //解析提示文本
        "count": res.data.total, //解析数据长度
        "data": res.data.list //解析数据列表
      };
    },
    response: {
      statusCode: 200 //成功的状态码，默认：0
      ,
    },
    where: {
      // userId: 'uidadmin',
      userId: $.parseJSON(localStorage.getItem('userInfo')).id
    },
    headers: { accessKey: localStorage.getItem('userToken') },
    contentType: 'application/json',
    cols: [
      [{
        field: 'index',
        title: '序号',
        align: 'center'
      }, {
        field: 'enterpriseUserName',
        title: '用户名',
        align: 'center',
      }, {
        field: 'companyTelephone',
        title: '手机号',
        align: 'center',
      }, {
        field: 'companyName',
        title: '企业名称',
        align: 'center',
      }, {
        field: 'companyIdentifer',
        title: '企业标识',
        align: 'center',
      }, {
        field: 'companyNature',
        title: '企业类型',
        align: 'center',
        templet: function (d) {
          switch (d.companyNature) {
            case '1':
              return '国有控股';
            case '2':
              return '民营控股';
            case '3':
              return '外商控股';
            case '4':
              return '事业单位';
            case '5':
              return '民营非盈利组织';
            default:
              return "";
          }
        }
      }, {
        field: 'addTime',
        title: '申请时间',
        align: 'center',
      }, {
        field: 'enterpriseUserStatus',
        title: '当前状态',
        align: 'center',
        templet: function (d) {
          if (d.enterpriseUserStatus == 'USERSTATUS_MORMAL') {
            return '正常使用'
          } else if (d.enterpriseUserStatus == 'USERSTATUS_LOCK') {
            return '锁定/禁用'
          } else if (d.enterpriseUserStatus == 'USERSTATUS_FROZEN') {
            return '冻结'
          } else if (d.enterpriseUserStatus == 'USERSTATUS_ABOLISH') {
            return '注销'
          } else {
            return "";
          }
        },
      }, {
        title: '操作',
        align: 'center',
        templet: function (d) {
          if (d.enterpriseUserStatus == 'USERSTATUS_MORMAL') {
            return '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>' +
              '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>' +
              '<a id="statusBtn" class="layui-btn layui-btn-warm layui-btn-xs" lay-event="changeStatus">禁用</a>';
          } else if (d.enterpriseUserStatus == 'USERSTATUS_LOCK') {
            return '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>' +
              '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>' +
              '<a id="statusBtn" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="changeStatus">启用</a>';
          } else {
            return '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>' +
              '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>' +
              '<a id="statusBtn" class="layui-btn layui-btn-xs layui-btn-disabled" lay-event="changeStatus">禁用</a>';
          }

        }
      }]
    ],
    method: 'post' //如果无需自定义HTTP类型，可不加该参数
    ,
    request: { //如果无需自定义请求参数，可不加该参数
      pageName: 'pageIndex', //页码的参数名称，默认：page
      limitName: 'pageSize' //每页数据量的参数名，默认：limit
    },

    page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
      groups: 3 //只显示 1 个连续页码
      ,
      first: '首页' //首页
      ,
      last: '尾页' //尾页
      ,
      limits: [5, 10, 15, 20, 30, 50] //返回条数
      ,
      limit: 10
    },
    loading: true //点击分页时跳转的进度条
    ,
    text: {
      none: '无数据'
    },
    done: function (res, curr, count) {
      console.log('表格数据', res);
      if (res.success == false && res.message.indexOf("Session") != "-1") {
        layer.confirm('Session已失效，请重新登录！', {
          title: '登录',
          shade: [1.0, '#fff'],
          skin: 'layui-layer-lan',
          btn: ['去登陆'] //按钮
        }, function () {
          if ($.parseJSON(localStorage.getItem('userInfo')).userType.indexOf("ADMIN") != "-1") {
            //跳转回管理员登录页
            // parent.location.href = "admin-login.html";
            parent.location.href = "../login.html";
          } else {
            //跳转回用户登录页
            parent.location.href = "../login.html";
          }
        }, function () { });
      }
    }
  });


  //触发行单击事件


  form.on('switch(isSwitch)', function (data) {
    // console.log('switch', data);
    var state1 = data.elem.checked ? true : false; //获取开关状态
    // console.log(data.elem.id);
    // console.log('state1', state1);
    let activeRow = data.value;
    // console.log('activeRow', activeRow)
    let tableBak = [];
    let dataBak = [];

    if (data.elem.id == 'editSwitch') {
      layui.table.cache.operationTemplateTable[activeRow - 1].notNull = state1;
      tableBak = layui.table.cache.operationTemplateTable;
      tableBak.forEach(item => {
        delete item.LAY_TABLE_INDEX
      })


      for (let i = 0; i < tableBak.length; i++) {
        dataBak.push(tableBak[i]);
      }


      layui.table.reload('operationTemplateTable', {
        data: dataBak
      });

    } else {//addSwitch
      layui.table.cache.templateTable[activeRow - 1].notNull = state1;
      tableBak = layui.table.cache.templateTable;
      tableBak.forEach(item => {
        delete item.LAY_TABLE_INDEX
      })


      for (let i = 0; i < tableBak.length; i++) {
        dataBak.push(tableBak[i]);
      }


      layui.table.reload('templateTable', {
        data: dataBak
      });

    }
  });



  //新增弹框中的表格

  table.on('tool(templateTable)', function (obj) {
    let data = obj.data; //获得当前行数据
    console.log('当前行数据', data);
    let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
    if (layEvent === 'delete') {
      layer.confirm('确定要删除吗？', {
        title: '删除',
        skin: 'layui-layer-lan',
        btn: ['删除', '取消']
      }, function () {
        //执行删除函数
        deleteData(data.id);
      }, function () { });
    }
  })

  //编辑弹框中的表格
  table.on('tool(operationTemplateTable)', function (obj) {
    // console.log(obj);
    let data = obj.data; //获得当前行数据
    // console.log(data);
    let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
    if (layEvent === 'delete') {
      layer.confirm('确定要删除吗？', {
        title: '删除',
        skin: 'layui-layer-lan',
        btn: ['删除', '取消']
      }, function (index) {
        //执行删除函数
        operateDelData(data, index);
      }, function () { });
    }
  })

  //点击工具栏(列表显示的表格)
  table.on('tool(dataTable)', function (obj) {
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'delete') { //删除
      layer.confirm('确定要删除吗？', {
        title: '删除',
        skin: 'layui-layer-lan',
        btn: ['删除', '取消']
      }, function () {
        //执行删除函数
        deleteData(data.enterpriseUserId, data.companyID);
      }, function () { });
    } else if (layEvent === 'edit') { //编辑
      layer.open({
        type: 1,
        shade: false,
        area: ['800px', 'auto'],
        title: '编辑',
        content: $('#operation_context'),
        cancel: function () {
          $('#operation_context').hide();
        },
        success: function (layero, index) {
          //调取数据回显接口
          let url = containercode_url + "/template/selectTemplate";

          function editCallBack (res) {
            if (res.success) {
              editConfirmTemplateId = res.data.id;
              console.log(res.data.templateInfo);
              //回显数据
              $("#operation_context").find(".templateName").val(res.data.templateName);
              $("#operation_context").find(".templateTitle").val(res.data.templateTitle);
              $("#operation_context").find(".templateDescribe").val(res.data.templateDescribe);
              //重载表格(刷新)
              table.reload('operationTemplateTable', {
                // data: [{ "field": "b", "index": 1, "maxLength": 2, "minLength": 0, "name": "j", "notNull": true }]
                data: JSON.parse(res.data.templateInfo)
              });
              //刷新表单渲染
              form.render();
            } else {
              layer.alert(res.message, {
                icon: 2,
                title: language.language1
              });
            }
          }
          myAjax(url, {
            "templateName": data.templateName //模板名称
          }, editCallBack);
        }
      });
    } else if (layEvent === 'changeStatus') { //改变按钮状态
      let enterprisesserstatus = "USERSTATUS_MORMAL";
      console.log('当前行数据', data);
      if (data.enterpriseUserStatus == 'USERSTATUS_MORMAL') {
        enterprisesserstatus = "USERSTATUS_LOCK";
      } else if (data.enterpriseUserStatus == 'USERSTATUS_LOCK') {
        enterprisesserstatus = "USERSTATUS_MORMAL";
      }

      //调取数据回显接口
      let url = containercode_url + "/enterprise/changeAccountState";
      function changeStatusCallBack (res) {
        // console.log('res', res);
        if (res.success) {
          $('#json-renderer').jsonViewer(res.data, { collapsed: false, withQuotes: true, withLinks: false });
          //表格重载
          table.reload('dataTable', {});
          //刷新表单渲染
          // form.render();
        } else {
          layer.alert(res.message, {
            icon: 2,
            title: language.language1
          });
        }
      }
      myAjax(url, {
        "userId": $.parseJSON(localStorage.getItem("userInfo")).id, //用户id, //用户id
        "enterpriseUserStatus": enterprisesserstatus, //企业账户状态
        "enterpriseUserId": data.enterpriseUserId //企业账户Id
      }, changeStatusCallBack);

    } else if (layEvent === 'detail') { //详情
      console.log('data', data);

      let companynature = '';
      let contactArr = data.contactIDPhoto.split(",");
      let corpArr = data.corpIDPhoto.split(",");
      switch (data.companyNature) {
        case '1':
          companynature = '国有控股';
          break;
        case '2':
          companynature = '民营控股';
          break;
        case '3':
          companynature = '外商控股';
          break;
        case '4':
          companynature = '事业单位';
          break;
        case '5':
          companynature = '民营非盈利组织';
          break;
      }

      console.log('companynature', companynature);


      layer.open({
        type: 1, //基本层类型 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        shade: false,
        area: ['800px', '711px'],
        title: '详情',
        content: $('#detail_context'),
        cancel: function () {
          $('#detail_context').hide();
        },
        success: function (layero, index) {
          //回显数据
          $("#detail_context").find(".companyIdentifer").val(data.companyIdentifer);
          $("#detail_context").find(".companyName").val(data.companyName);
          $("#detail_context").find(".companyNature").val(data.companyNature);
          $("#detail_context").find(".companyID").val(data.companyID);
          $("#detail_context").find(".registeredAddress").val(data.registeredAddress);
          $("#detail_context").find(".companyTelephone").val(data.companyTelephone);
          $("#detail_context").find(".officialWebsite").val(data.officialWebsite);
          $("#detail_context").find(".companyIntroduce").val(data.companyIntroduce);
          $("#detail_context").find(".corpName").val(data.corpName);
          $("#detail_context").find(".corpIDNum").val(data.corpIDNum);
          $("#detail_context").find(".contactName").val(data.contactName);
          $("#detail_context").find(".companyTelephone").val(data.companyTelephone);
          $("#detail_context").find(".contactEmail").val(data.contactEmail);
          $("#detail_context").find(".companyName").val(data.companyName);
          $("#detail_context").find(".companyNature").val(companynature);
          $("#detail_context").find(".contactIDNum").val(data.contactIDNum);
          $("#detail_context").find(".companyIDPhoto").attr('src', data.companyIDPhoto);
          $("#detail_context").find(".corpIDPhotoZ").attr('src', corpArr[0]);
          $("#detail_context").find(".corpIDPhotoF").attr('src', corpArr[1]);
          $("#detail_context").find(".contactIDPhotoZ").attr('src', contactArr[0]);
          $("#detail_context").find(".contactIDPhotoF").attr('src', contactArr[1]);
        }
      })

    } else if (layEvent === 'exportTemplate') { //导出模板
      //导出为 csv 文件
      console.log('表格的配置', tableIns.config);
      table.exportFile(editTableInts.config.id, tableIns.config.cols); //data 为该实例中的任意数量的数据
    }
  });

  table.on('edit(templateTable)', function (obj) {
    console.log(obj);
  });


  //表格搜索
  $("#searchBtn").click(function () {
    // console.log('输入框的值', $("#boxNo").val());
    table.reload('dataTable', {
      where: {
        "searchParam": $("#boxNo").val()
      }
    });
  });

  $("#boxNo").change(function () {
    // console.log($("#boxNo").val());
    if ($("#boxNo").val() == '') {
      tableIns.reload({
        url: containercode_url + "/enterprise/list",
        parseData: function (res) { //res 即为原始返回的数据
          return {
            "code": res.errorCode, //解析接口状态
            "msg": res.message, //解析提示文本
            "count": res.data.total, //解析数据长度
            "data": res.data.list //解析数据列表
          };
        },
        response: {
          statusCode: 200 //成功的状态码，默认：0
          ,
        },
        page: {
          curr: 1 //重新从第 1 页开始
        },
        method: 'post' //如果无需自定义HTTP类型，可不加该参数
        ,
        request: { //如果无需自定义请求参数，可不加该参数
          pageName: 'pageIndex', //页码的参数名称，默认：page
          limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
      });
    }
  });

  //导出集装箱列表
  $("#exportBtn").click(function () {
    var beginTime = $("#time").val() != "" ? locationTimeChangeUtcTime($("#time").val().split(" - ")[0]) : "";
    var endTime = $("#time").val() != "" ? locationTimeChangeUtcTime($("#time").val().split(" - ")[1]) : "";

    layer.msg(
      '正在导出，请稍等..', {
      icon: 1,
      time: 3000,
      shade: 0,
      end: function () {
        //导出
        location.href = containercode_url + "/opertion/downOperationList?language=" + language.langType +
          "&userToken=" + localStorage.getItem('userToken') + "&boxNo=" + $.trim($("#boxNo").val()) +
          "&boxModel=" + $("#boxModel").val() + "&boxSize=" + $("#boxSize").val() + "&beginTime=" + beginTime +
          "&endTime=" + endTime;
      }
    });
  });


  //批量删除
  $("#batchDelete").click(function () {
    //获取选中行的数据
    var checkStatus = table.checkStatus('dataTable');
    if (checkStatus.data.length == 0) {
      layer.alert('至少选中一条数据！', {
        icon: 0,
        title: language.language1
      });
    } else {
      layer.confirm('确定要删除吗？', {
        title: '删除',
        skin: 'layui-layer-lan',
        btn: ['删除', '取消']
      }, function () {
        var idList = [];
        for (var i = 0; i < checkStatus.data.length; i++) {
          idList.push(checkStatus.data[i]["id"]);
        }
        //执行删除函数
        deleteData(idList);
      }, function () { });
    }
  });

  //列表删除
  function deleteData (enterpriseUserId, companyID) {
    let url = containercode_url + "/enterprise/deleteEnterprise";

    function delCallBack (res) {
      if (res.success) {
        layer.msg('删除成功！', {
          icon: 1,
          time: 500,
          shade: 0,
          end: function () {
            //表格重载
            table.reload('dataTable', {});
          }
        });
      } else {
        layer.alert(res.message, {
          icon: 2,
          title: language.language1
        });
      }
    }
    myAjax(url, {
      "userId": $.parseJSON(localStorage.getItem("userInfo")).id, //用户id
      enterpriseUserId, //企业账户Id
      companyID //企业证件号(统一社会信用代码)
    }, delCallBack);
  }

  // 编辑列表删除
  function operateDelData (data, idx) {
    // console.log(data);
    let templateInfo = [];
    let newTemplateInfo = [];
    templateInfo = layui.table.cache.operationTemplateTable;
    // console.log(templateInfo);
    newTemplateInfo = templateInfo.filter(item => {
      return item.index !== data.index
    })
    newTemplateInfo.forEach(item => {
      delete item.LAY_TABLE_INDEX
    })
    console.log('newTemplateInfo', newTemplateInfo);
    table.reload('operationTemplateTable', {
      data: newTemplateInfo
    })

    layer.close(idx);

  }






  //导出Excel
  $("#exportExcel").click(function () {
    // window.open(containercode_url + "/enterprise/exportEnterpriseList?searchParam=");
    // window.open('http://10.43.10.102:8085/containercode/enterprise/exportEnterpriseList?searchParam=');
    // let url = containercode_url + "/enterprise/exportEnterpriseList?searchParam=";
    if ($("#boxNo").val() !== "") {
      // console.log('输入框不为空')
      let queryparam = $("#boxNo").val();
      let url = containercode_url + "/enterprise/exportEnterpriseList?searchParam=" + queryparam;
      window.open(url);
    } else {
      // console.log('输入框为空')
      let url = containercode_url + "/enterprise/exportEnterpriseList?searchParam=";
      window.open(url);
    }
  });






})
